import axios from "axios";
import constant from "./constant";
//处理url参数
import qs from "qs";

axios.defaults.baseURL = constant.baseURL;

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    if (response.data !== null && response.data.hasOwnProperty("code") && response.data.code !== 200) {
        if (response.data.code === 300) {
        }
        return Promise.reject(response.data.msg);
    } else {
        return response;
    }
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

// 当data为URLSearchParams对象时设置为application/x-www-form-urlencoded;charset=utf-8
// 当data为普通对象时，会被设置为application/json;charset=utf-8


export default {
    request(option) {
        let contentType
        if (option.contentType) {
            contentType = option.contentType
        } else {
            contentType = "application/json;charset=UTF-8"
        }
        // option.url = constant.baseURL + option.url
        return new Promise((resolve, reject) => {
            axios({
                url: option.url,
                method: option.method,
                headers: {
                    "Authorization": localStorage.getItem("token"),
                    "contentType": contentType
                },
                params: option.method === 'get' ? option.data : {},
                data: option.method === 'post' ? option.data : {}
            }).then(res => {
                resolve(res.data);
            }).catch(err => {
                reject(err);
            });
        })
    },
}
